package filter;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import java.util.ArrayList;

public final class FileOperation {
	private String filePath; 
	private File file;
	private final HashMap<String, String> fileType = new HashMap<String, String>();
 	
	FileOperation(String path) {
		file = new File(path);
		filePath = path;
		this.inputHeadMessage();
	}

	private void inputHeadMessage() {
		fileType.put("504B0304", "zip");
		fileType.put("464C5601", "flv");
		fileType.put("00000000", "txt");
		fileType.put("FFD8FF", "jpg");
		fileType.put("89504E47", "png");
		fileType.put("47494638", "gif");
		fileType.put("49492A00", "tif");
		fileType.put("424D", "bmp");
		fileType.put("41433130", "dwg");
		fileType.put("38425053", "psd");
		fileType.put("7B5C727466", "rtf");
		fileType.put("3C3F786D6C", "xml");
		fileType.put("68746D6C3E", "html");
		fileType.put("44656C69766572792D646174653A", "eml"); // 邮件
		fileType.put("D0CF11E0", "doc");
		fileType.put("5374616E64617264204A", "mdb");
		fileType.put("252150532D41646F6265", "ps");
		fileType.put("255044462D312E", "pdf");
		fileType.put("504B0304", "docx");
		fileType.put("52617221", "rar");
		fileType.put("57415645", "wav");
		fileType.put("41564920", "avi");
		fileType.put("2E524D46", "rm");
		fileType.put("000001BA", "mpg");
		fileType.put("000001B3", "mpg");
		fileType.put("6D6F6F76", "mov");
		fileType.put("3026B2758E66CF11", "asf");
		fileType.put("4D546864", "mid");
		fileType.put("1F8B08", "gz");
		fileType.put("4D5A9000", "exe/dll");
		fileType.put("75736167", "txt");
	}

	public boolean isDirectory() {
		return file.isDirectory();
	}
	
	public String getFileType() {
		return this.fileType.get(this.getFileHeader());
	}
	
	public String getFileHeader() {
		FileInputStream is = null;
		String value = null;
		
		try {
			is = new FileInputStream(this.filePath);
			byte[] b = new byte[4];
			is.read(b, 0, b.length);
			value = bytesToHexString(b);
		} catch(FileNotFoundException e) {
			System.out.println("File path found ERROR!\n"
					+ "Check it & retry");
			System.exit(-1);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(is != null) {
				try {
					is.close();
				} catch(IOException e) {
					e.printStackTrace();
				}
			}
		}
		return value;
	}
	
	public void renameFile(String Name) {
		File newName = new File(this.file.getParent() + Name);
		this.file.renameTo(newName);
	}
	
	public void chgHdAuFile() {
		
		if(file.isHidden()) {
			try {
				Runtime.getRuntime().exec("attrib " + file.getAbsolutePath() + " -H");
			} catch(IOException e) {
				e.printStackTrace();
			}
		} else {
			try {
				Runtime.getRuntime().exec("attrib " + file.getAbsolutePath() + " +H");
			} catch(IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void delFile() {
		delFile(this.file.getAbsolutePath());
	}
	
	private void delFile(String path) {
		File f = new File(path);
		
		if(f.isDirectory()) {
			String[] list = f.list();
			for(String eachFile : list) {
				delFile(path + "//" + eachFile);
			}
		}
		f.delete();
	}
	
	public void chgRdAuFile() {
		if(this.file.canWrite()) {
			file.setReadOnly();
		} else {
			file.setWritable(true);
		}
	}
	
	public String getFileSuffix() {
		return file.getName().substring(file.getName().lastIndexOf(".")).substring(1);
	}
	
	private static String bytesToHexString(byte[] src) {
		StringBuilder builder = new StringBuilder();
		
		if(src == null || src.length <= 0) {
			return null;
		}
		String hv;
		
		for(int i = 0; i < src.length; ++i) {
			hv = Integer.toHexString(src[i] & 0xFF).toUpperCase();
			
			if(hv.length() < 2) {
				builder.append(0);
			}
			
			builder.append(hv);
		}
		return builder.toString();
	}
	
	public void compress(String outputZip) throws FileNotFoundException {
		long startTime = System.currentTimeMillis();
		File temp = new File(outputZip);
		
		if(!temp.exists()) {
			try {
				temp.createNewFile();
			} catch(IOException e) {
				e.printStackTrace();
			}
		}
		
		if(this.file.exists()) {
			
			try{
				OutputStream outputStream = new FileOutputStream(outputZip);
				ZipOutputStream zOs = new ZipOutputStream(outputStream);
				doCompress(zOs, this.file, file.getName());
				zOs.close();
			} catch (IOException e) {
				System.out.println("The file path you want to output might not exists!");
				e.printStackTrace();
			}
			System.out.println("Compress complete! Use : " + (System.currentTimeMillis() - startTime) + "m secs");
		} else {
			throw new FileNotFoundException("The file you input is not exists!");
		}
	}
	
	private void doCompress(ZipOutputStream zOs, File files, String addPath) throws IOException {
		if(files.isDirectory()) {
			File[] fileList = files.listFiles();
			
			for(File f : fileList) {
				if(f.isDirectory()) {
					doCompress(zOs, f, addPath + f.getName() + File.separator);
				} else {
					doCompress(zOs, f, addPath + f.getName());
				}
			}
		} else {
			zOs.putNextEntry(new ZipEntry(addPath));
			BufferedInputStream buffer = new BufferedInputStream(
					new FileInputStream(files));
			
			byte[] buf = new byte[1024 * 8];
			int len = 0;
			
			while((len = buffer.read(buf)) != -1) {
				zOs.write(buf, 0, len);
			}
			buffer.close();
		}
	}
	
	@Override
	public String toString() {
		ArrayList<String> attribute = new ArrayList<String>();
		attribute.add("FileName : " + file.getName());
		attribute.add("FilePath : " + filePath);
		attribute.add("IsHidden? : " + file.isHidden());
		
		if(!this.file.isDirectory()) {
			attribute.add("FileType : " + this.getFileType());
			attribute.add("FileSize : " + file.length() + " kb");
			attribute.add("IsOnlyRead? : " + !file.canWrite());
		}
		return attribute.toString();
	}

}
